package com.dk.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter({"/travelRoute/insertInfo","/travelRoute/insertInfo"})
public class StringFilter implements Filter {
    List<String> msgList = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        msgList.add("你");
        msgList.add("WTM");
        msgList.add("小傻瓜");
        System.out.println("过滤器初始化完成");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("进入过滤器方法");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String message = request.getParameter("routeintroduce");
        if(message != null && !"".equals(message)) {
            for (String m : msgList) {
                if(message.contains(m)) {
                    String str = "";
                    for (int j = 0; j < m.length(); j++) {
                        str += "*";
                    }
                    message = message.replace(m, str);
                    request.setAttribute("newMessage", message);
                }
            }
        }

        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        System.out.println("执行过滤器销毁");
    }
}
